package com.zhwmall.product.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhwmall.common.entity.product.AttrAttrgroupRelationEntity;
import com.zhwmall.common.entity.product.AttrEntity;
import com.zhwmall.common.entity.product.AttrGroupEntity;
import com.zhwmall.common.entity.product.CategoryEntity;
import com.zhwmall.common.vo.AttrGroupWithAttrVo;
import com.zhwmall.product.dao.AttrAttrgroupRelationDao;
import com.zhwmall.product.dao.AttrDao;
import com.zhwmall.product.dao.AttrGroupDao;
import com.zhwmall.product.dao.CategoryDao;
import com.zhwmall.product.service.AttrGroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Override
    public IPage<AttrGroupEntity> pageList(Map<String, Object> params, long catId) {
        IPage<AttrGroupEntity> page = new Page<>(Long.parseLong((String) params.get("limit")), Long.parseLong((String) params.get("page")));
        String input = (String) params.get("input");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(input)){
            wrapper.and((obj)->{
                obj.eq("attr_group_id", input.trim())
                    .or()
                    .like("attr_group_name", input.trim())
                    .or()
                    .like("descript", input.trim());
            });
        }
        if (catId == 0){
            IPage<AttrGroupEntity> iPage = baseMapper.selectPage(page, wrapper);
            List<AttrGroupEntity> entities = iPage.getRecords();
            entities.forEach((item)->{
                List<String> list =  CollUtil.newArrayList();
                Long catelogId = item.getCatelogId();

                List<String> names = findCateLogNamesByCatId(catelogId, list);

                List<String> reverse = CollectionUtil.reverse(names);

                item.setCatelogNames(reverse.toArray(new String[reverse.size()]));

            });
            return iPage;
        }else {
            wrapper.eq("catelog_id", catId);
            return baseMapper.selectPage(page, wrapper);
        }
    }

    @Override
    public Long[] findParent(Long catelogId) {
        CategoryEntity entity = categoryDao.selectById(catelogId);
        List<Long> list = CollUtil.newArrayList();
        List<Long> longList = CollectionUtil.reverse(findParentById(entity, list));
        return longList.toArray(new Long[longList.size()]);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        if (CollUtil.isNotEmpty(entities)){
            List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            return attrDao.selectBatchIds(attrIds);
        }
        return null;
    }

    @Override
    public IPage<AttrEntity> getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        IPage<AttrEntity> page = new Page<>(Long.parseLong((String) params.get("limit")), Long.parseLong((String) params.get("page")));
        String key = (String) params.get("input");

        // 1、当前属性只能关联自己所属分类
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId(); // 获得分类 Id
        // 2、当前分组只能关联别的分组没有引用的属性
        // 2、1 当前分类下的其它分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupId = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        // 2、2 这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", groupId));

        List<Long> attrIds = null;
        if (CollUtil.isNotEmpty(relationEntities)){
            attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        }
        // 2、3 从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", 1)
                .eq("enable", 1);

        if (CollUtil.isNotEmpty(attrIds)) {
           wrapper.notIn("attr_id", attrIds);
        }
        if (StrUtil.isNotEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id", key)
                        .or()
                        .eq("attr_name", key);
            });
        }

        return attrDao.selectPage(page, wrapper);
    }

    @Override
    public List<AttrGroupWithAttrVo> getAttrGroupWithAttrByCatelogId(Long catelogId) {

        List<AttrGroupEntity> attrGroupEntities = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (CollUtil.isNotEmpty(attrGroupEntities)){
            return attrGroupEntities.stream().map(item->{
                AttrGroupWithAttrVo vo = new AttrGroupWithAttrVo();
                BeanUtils.copyProperties(item, vo);

                List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", item.getAttrGroupId()));

                if (CollUtil.isNotEmpty(relationEntities)){
                    List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
                    List<AttrEntity> attrEntities = attrDao.selectBatchIds(attrIds);
                    vo.setAttrs(attrEntities);
                }
                return vo;
            }).collect(Collectors.toList());
        }

        return null;
    }


    // [2, 34, 255]
    public List<Long> findParentById(CategoryEntity entity, List<Long> list){
        list.add(entity.getCatId());
        if (entity.getParentCid() != 0){
            CategoryEntity categoryEntity = categoryDao.selectById(entity.getParentCid());
            findParentById(categoryEntity, list);
        }
        return list;
    }

    // [图书, 电子书刊, 电子书]
    public List<String> findCateLogNamesByCatId(Long catelogId, List<String> list){
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        list.add(categoryEntity.getName());
        if (categoryEntity.getParentCid() != 0){
            list.add("/");
            findCateLogNamesByCatId(categoryEntity.getParentCid(), list);
        }
        return list;
    }
}